package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.ReportApi;
import com.tanhua.model.mongo.Report;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;

@DubboService
public class ReportApiImpl implements ReportApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询该用户做该问卷的鉴定结果
     *
     * @param userId
     * @param questionnaireId
     * @return
     */
    @Override
    public Report findByUserIdAndQuestionnaireId(Long userId, String questionnaireId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("questionnaireId").is(new ObjectId(questionnaireId)));
        return mongoTemplate.findOne(query, Report.class);
    }

    /**
     * 修改或增加报告并返回
     * @param report
     * @return
     */
    @Override
    public Report addAndUpdateReport(Report report) {
        Query query=new Query();
        query.addCriteria(Criteria.where("userId").is(report.getUserId()).and("questionnaireId").is(report.getQuestionnaireId()));
        Report one = mongoTemplate.findOne(query, Report.class);
        //如果查询结果为空则添加
        Report newReport=null;
        if(StringUtils.isEmpty(one)){
            newReport = mongoTemplate.insert(report);
        }else {

            Update update=new Update();
            update.set("questionnaireId",report.getQuestionnaireId());
            update.set("conclusion",report.getConclusion());
            update.set("score",report.getScore());
            update.set("cover",report.getCover());
            update.set("level",report.getLevel());
            update.set("updated",report.getUpdated());
            newReport = mongoTemplate.findAndModify(query, update, Report.class);
        }

        return newReport;
    }
}
